﻿Imports System.Collections.ObjectModel
Imports System.ComponentModel
Imports System.Windows.Threading
Imports System.Net
Imports System.Text
Imports System.Threading.Tasks

Public Class ZipCityQuery
    Implements INotifyPropertyChanged

    Private _ziplist As ObservableCollection(Of ZipCityModel)
    Private _dp As Dispatcher

    Public Sub New(dp As Dispatcher)
        _dp = dp
    End Sub

    Public Property ItemsList As ObservableCollection(Of ZipCityModel)
        Get
            Return _ziplist
        End Get
        Set(value As ObservableCollection(Of ZipCityModel))
            _ziplist = value
            NotifyPropertyChanged("ItemsList")
        End Set
    End Property

    Public Sub GetZIPListAsync(city As String)
        task.Factory.StartNew(Sub()
                                  GetZips(city)
                              End Sub)
    End Sub

    Private Sub GetZips(city As String)
        Dim timestamp As String = DateTime.UtcNow.ToString("{0:R}")
        Dim req = CreateWebRequest("http://www.postdirekt.de/plzserver/PlzAjaxServlet?q=" + city + "&limit=10&timestamp=" + timestamp + "&autocomplete=plz&plz_city=" + city, "")
        Dim resp = req.GetResponse()
        Dim sr As New IO.StreamReader(resp.GetResponseStream())
        Dim c As New Collection(Of String)
        While sr.Peek <> -1 AndAlso c.Count < 10
            c.Add(sr.ReadLine)
        End While
        sr.Close()
        Dim temp As New ObservableCollection(Of ZipCityModel)
        For Each s In c
            Dim item() = s.Split("|")
            Dim zip = item(0)
            If String.IsNullOrEmpty(item(2)) AndAlso String.IsNullOrEmpty(item(3)) Then
                temp.Add(New ZipCityModel(item(1), item(0)))
            ElseIf String.IsNullOrEmpty(item(2)) AndAlso String.IsNullOrEmpty(item(3)) = False Then
                temp.Add(New ZipCityModel(item(1) + " " + item(3), item(0)))
            ElseIf String.IsNullOrEmpty(item(2)) = False Then
                'Stadtteile
                If String.IsNullOrEmpty(item(3)) = False Then
                    temp.Add(New ZipCityModel(item(2) + " (Ortsteil von " + item(1) + " " + item(3) + ")", item(0)))
                Else
                    temp.Add(New ZipCityModel(item(2) + " (Ortsteil von " + item(1) + ")", item(0)))
                End If
            End If
        Next
        _dp.BeginInvoke(Sub()
                            ItemsList = temp
                        End Sub)
    End Sub

    Private Function CreateWebRequest(url As String, content As String) As HttpWebRequest
        Dim req As HttpWebRequest = HttpWebRequest.Create(url)
        req.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11"
        req.Method = "GET"
        req.ContentType = "application/x-www-form-urlencoded"
        req.AllowAutoRedirect = False
        If Not String.IsNullOrEmpty(content) Then
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(content)
            req.ContentLength = byteArray.Length
            req.GetRequestStream().Write(byteArray, 0, byteArray.Length)
        End If
        Return req
    End Function

    Protected Sub NotifyPropertyChanged(info As [String])
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(info))
    End Sub

    Public Event PropertyChanged(sender As Object, e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
End Class
